//
//  WalletInfoViewController.m
//  Bees
//
//  Created by NowYouCanSee on 2018/12/27.
//  Copyright © 2018 xiaohan. All rights reserved.
//

#import "WalletInfoViewController.h"
#import "UIColor+GradualChanging.h"
#import "MineSwitchItem.h"
#import "WalletTool.h"
#import "ChangePwdViewController.h"
#import "EOSService.h"
#import "ResourcesDetailsViewController.h"
#import "WhiteListViewController.h"
#import "InputBeesKeyViewController.h"
#import "ForgetPwdViewController.h"
#import "XHPermissionsViewController.h"
@interface WalletInfoViewController ()
@property (nonatomic,strong) UILabel *moneyLab;
@property (nonatomic,strong) UILabel *unitLab;
@property (nonatomic,strong) UILabel *accountLab;
@property (nonatomic,strong) EOSService *eosService;
@end

@implementation WalletInfoViewController
- (instancetype)init
{
    return [super initWithStyle:UITableViewStylePlain];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self getAccountInfo];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    MineSwitchItem *item4  = (MineSwitchItem *)[[self.sections objectAtIndex:0].items lastObject];
    item4.open = [WalletTool isUseFingerprintCurrentWallet:self.wallet];
    [self.tableView reloadData];
}
- (void)getAccountInfo{
    [self.eosService getAccountInfoComplete:^(BOOL success, NSString * _Nonnull errorMsg) {
        if (success) {
            self.moneyLab.text = self.eosService.accountResult.core_liquid_balance;
            self.unitLab.text = @"";
            self.accountLab.text = self.wallet.wallet_name;
        }
        else{
            [self.view makeToast:errorMsg];
        }
    }];
}

- (void)setupUI{
    self.customNavigationBar.height = .01;
    self.leftBackImg = @"white_back";
    self.isShowLeftBack = YES;
    [self.tableView registerClass:UITableViewHeaderFooterView.class forHeaderFooterViewReuseIdentifier:@"head"];
    self.StatusBarStyle = UIStatusBarStyleLightContent;
    UIView *headView= [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, AdaptedWidth(195))];
    self.moneyLab = [UILabel new];
    self.moneyLab.textColor = UIColorHex(#FFFFFF);
    self.moneyLab.font = kBoldFont(24);
    [headView addSubview:self.moneyLab];
    [self.moneyLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.centerY.mas_offset(0);
    }];
    self.unitLab = [UILabel new];
    self.unitLab.textColor = UIColorHex(#FFFFFF);
    self.unitLab.font = kDefaultFont(13);
    [headView addSubview:self.unitLab];
    [self.unitLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.moneyLab.mas_bottom).offset(-4);
        make.left.equalTo(self.moneyLab.mas_right).offset(AdaptedWidth(8));
    }];
//    self.unitLab.text = @"USD";
    
    self.accountLab = [UILabel new];
    self.accountLab.textColor = UIColorHex(#FFFFFF);
    self.accountLab.font = kDefaultFont(13);
    [headView addSubview:self.accountLab];
    [self.accountLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(AdaptedWidth(-13));
        make.left.mas_equalTo(kNormalSpace);
    }];
    self.tableView.tableHeaderView = headView;
    [headView.layer insertSublayer:[UIColor setGradualChangingFrame:CGRectMake(0, 0, kScreenWidth, headView.height) fromColor:[kGradientColors firstObject] toColor:[kGradientColors lastObject]] atIndex:0];
    kWeakSelf(self);
    LMJWordArrowItem *item0 = [LMJWordArrowItem itemWithTitle:XLocalized(@"修改密码") subTitle:@""];
    item0.itemOperation = ^(NSIndexPath *indexPath) {
        ChangePwdViewController *vc = [ChangePwdViewController new];
        vc.wallet = weakself.wallet;
        [weakself.navigationController pushViewController:vc animated:YES];
    };
    LMJWordArrowItem *item1 = [LMJWordArrowItem itemWithTitle:XLocalized(@"导出私钥") subTitle:@""];
    item1.itemOperation = ^(NSIndexPath *indexPath) {
        [WalletTool checkPrivateInputPasswordWith:weakself.wallet complete:^(BOOL result, NSString * _Nonnull privateKey) {
            if (result) {
                InputBeesKeyViewController *vc = [InputBeesKeyViewController new];
                vc.private_key = privateKey;
                [weakself.navigationController pushViewController:vc
                                                         animated:YES];
            }
        }];
    };
    
    LMJWordArrowItem *item2 = [LMJWordArrowItem itemWithTitle:XLocalized(@"资源管理") subTitle:@""];
    item2.itemOperation = ^(NSIndexPath *indexPath) {
        ResourcesDetailsViewController *vc=[ResourcesDetailsViewController new];
        vc.wallet = weakself.wallet;
        [weakself.navigationController pushViewController:vc animated:YES];
    };
    LMJWordArrowItem *item3 = [LMJWordArrowItem itemWithTitle:XLocalized(@"权限管理") subTitle:@""];
    item3.itemOperation = ^(NSIndexPath *indexPath) {
        XHPermissionsViewController *vc = [XHPermissionsViewController new];
        vc.wallet = weakself.wallet;
        [weakself.navigationController pushViewController:vc animated:YES];
    };
    
    MineSwitchItem *item4 = [MineSwitchItem itemWithTitle:kIsIphoneX?XLocalized(@"面容识别"):XLocalized(@"指纹识别") isOpen:[WalletTool isUseFingerprintCurrentWallet:self.wallet]];
    item4.SwitchBlock = ^(MineSwitchItem *item) {
        if (item.open) {
            [WalletTool useFingerprintCurrentWallet:self.wallet complete:^(BOOL result,NSString*pwd) {
                item.open = result;
                [self.tableView reloadData];
            }];
        }else{
            [WalletTool unUseFingerprintCurrentWallet:self.wallet complete:^(BOOL result,NSString*pwd) {
                item.open = !result;
                [self.tableView reloadData];
            }];
        }
    };
    LMJWordArrowItem *item5 = [LMJWordArrowItem itemWithTitle:XLocalized(@"白名单列表") subTitle:@""];
    item5.itemOperation = ^(NSIndexPath *indexPath) {
        WhiteListViewController *vc = [[WhiteListViewController alloc]initWithStyle:UITableViewStyleGrouped];
        vc.wallet = weakself.wallet;
        [weakself.navigationController pushViewController:vc animated:YES];
    };
    
    LMJItemSection *section = [LMJItemSection sectionWithItems:@[item0,item1,item2,item3,item5,item4] andHeaderTitle:nil footerTitle:nil];
    [self.sections addObject:section];
    
    UIView *footV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, AdaptedWidth(130))];
    footV.backgroundColor = UIColor.whiteColor;
    XThemeFlatButton *footBtn = [XThemeFlatButton button];
    [footV addSubview:footBtn];
    footBtn.frame = CGRectMake(kNormalSpace, AdaptedWidth(30), kScreenWidth-2*kNormalSpace, AdaptedWidth(40));
    [footBtn setTitle:XLocalized(@"删除钱包") forState:UIControlStateNormal];
    self.tableView.tableFooterView = footV;
    [footBtn addTapBlock:^(UIButton * _Nonnull btn) {
        [XAlertTool alertTitle:@"确定删除钱包？" message:nil cancelAction:^{
        } sureAction:^{
            [WalletTool alertCheckPasswordIsNeedShowUseFingerprint:NO Wallet:weakself.wallet complete:^(BOOL result,NSString*pwd) {
                if (result) {
                    if ([[XHDataBaseManager shareInstance]removeWallet:weakself.wallet.wallet_uid]) {
                        if ([weakself.wallet.wallet_uid isEqualToString:CURRENT_WALLET_ID]) {
                            [WalletTool changeCurrentWallet];
                        }
                        [[WalletTool sharedWalletTool].walletUseFingerprint removeObjectForKey:self.wallet.wallet_uid];
                        [kAppWindow makeToast:XLocalized(@"删除成功!")];
                        [weakself backBtnClicked];
                    }
                }
            }];
        }];
        
    }];
    
    UIButton *forgetBtn = [UIButton new];
    [forgetBtn setTitle:XLocalized(@"忘记密码?") forState:UIControlStateNormal];
    [forgetBtn setTitleColor:kColorMain forState:UIControlStateNormal];
    [footV addSubview:forgetBtn];
    forgetBtn.titleLabel.font = kDefaultFont(13);
    [forgetBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.top.equalTo(footBtn.mas_bottom);
    }];
    
    [forgetBtn addTapBlock:^(UIButton * _Nonnull btn) {
        ForgetPwdViewController *vc = [ForgetPwdViewController new];
        vc.wallet = weakself.wallet;
        [weakself.navigationController pushViewController:vc animated:YES];
    }];
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UITableViewHeaderFooterView *headV = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"head"];
    headV.contentView.backgroundColor = UIColor.whiteColor;
    UIImageView*keyV = [headV.contentView viewWithTag:1001];
    if (!keyV) {
        keyV = [UIImageView new];
        keyV.tag = 1001;
        keyV.image = IMAGE_NAMED(@"yellow_key");
        [headV.contentView addSubview:keyV];
        [keyV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.mas_equalTo(AdaptedWidth(20));
            make.size.mas_equalTo(CGSizeMake(AdaptedWidth(10), AdaptedWidth(10)));
        }];
    }
    UILabel *keyLab = [headV.contentView viewWithTag:1002];
    if (!keyLab) {
        keyLab = [UILabel new];
        keyLab.tag = 1002;
        keyLab.textColor = UIColorHex(#FFAE00);
        keyLab.font = kDefaultFont(13);
        keyLab.lineBreakMode = NSLineBreakByTruncatingMiddle;
        [headV.contentView addSubview:keyLab];
        [keyLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(keyV.mas_right).offset(AdaptedWidth(10));
            make.centerY.equalTo(keyV.mas_centerY);
            make.width.mas_equalTo(AdaptedWidth(120));
        }];
        keyLab.text = self.wallet.wallet_public_key;
    }
    UIButton*copyBtn = [headV.contentView viewWithTag:1003];
    if (!copyBtn) {
        copyBtn = [UIButton new];
        copyBtn.tag = 1003;
        [copyBtn setImage:IMAGE_NAMED(@"yellow_copy") forState:UIControlStateNormal];
        [headV.contentView addSubview:copyBtn];
        [copyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(keyLab.mas_right).offset(AdaptedWidth(0));
            make.centerY.equalTo(keyLab.mas_centerY);
            make.size.mas_equalTo(CGSizeMake(AdaptedWidth(35), AdaptedWidth(35)));
        }];
        kWeakSelf(self);
        [copyBtn addTapBlock:^(UIButton * _Nonnull btn) {
            if (keyLab.text.length) {
                UIPasteboard *pab = [UIPasteboard generalPasteboard];
                [pab setString:keyLab.text];
                if (pab == nil) {
                    [weakself.view makeToast:XLocalized(@"复制失败!")];
                }else
                {
                    [weakself.view makeToast:XLocalized(@"复制成功!")];
                }
            }
        }];
    }
//    yellow_key
    return headV;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return AdaptedWidth(60);
}
//- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
//    return .01f;
//}


#pragma mark - getter
- (EOSService *)eosService{
    if (!_eosService) {
        _eosService = [EOSService new];
        _eosService.wallet = self.wallet;
    }
    return _eosService;
}
@end
